import urllib2
from lxml import etree

url= 'http://xoap.weather.com/weather/local/BEXX0013?cc=*&dayf=5&link=xoap&unit=m&prod=xoap&par=1275223444&key=03c0830e175392b2'
iconpath= 'http://s.imwx.com/v.20100719.135915/img/wxicon/130/%s.png'

class Units():
  def __init__(self, node):
    self.temperature = node.xpath('ut')[0].text

class ForeCast():
  def __init__(self, node, units, part):
    self.hi = node.xpath('hi')[0].text
    self.low = node.xpath('low')[0].text
    self.sunr = node.xpath('sunr')[0].text
    self.suns = node.xpath('suns')[0].text
    partn = node.xpath('part')[part]
    self.description = partn.xpath('t')[0].text
    self.icon =iconpath%(partn.xpath('icon')[0].text)
    
    self.temperature = (self.hi if part == 0 else self.low) + units.temperature
    self.sun = self.sunr if part == 0 else self.suns
  def __repr__(self):
    s = ', '.join([self.name, self.temperature, self.description, self.icon, self.sun])
    return '('+s+')'
    
class ForeCastCurrent():
  def __init__(self, node, units):
    self.location = node.xpath('obst')[0].text
    self.temperature = node.xpath('tmp')[0].text + units.temperature
    self.feels_like = node.xpath('flik')[0].text + units.temperature
    self.description = node.xpath('t')[0].text
    self.icon =iconpath%(node.xpath('icon')[0].text)
  def __repr__(self):
    s = ', '.join([self.name, self.location, self.temperature, self.feels_like, self.description, self.icon])
    return '('+s+')'

def get_weather():
  req = urllib2.Request(url)
  r = urllib2.urlopen(req)
  data = r.read()
  tree = etree.fromstring(data)
  
  node = tree.xpath('/weather/head')
  units = Units(node[0])
  
  forecasts = []
  current = tree.xpath('/weather/cc')
  forecasts.append(ForeCastCurrent(current[0], units))
  r = tree.xpath('/weather/dayf/day')
  for i, node in enumerate(r):
      if i != 0:
        forecasts.append(ForeCast(node, units, 0))
      forecasts.append(ForeCast(node, units, 1))
  forecasts = forecasts[:3]
  for f, n in zip(forecasts, ['Current', 'Tonight', 'Tomorrow']):
    f.name = n
  return forecasts


if __name__ in ('__main__'):
    forecasts = get_weather()
    print forecasts
